package cn.q3c.download.spider;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.xBaseJ.DBF;
import org.xBaseJ.xBaseJException;

import cn.keyvalue.ccf.common.object.Hyperlink;
import cn.keyvalue.ccf.common.object.ListPage;
import cn.q3c.download.api.DownloadAPI;
import cn.q3c.download.base.BaseSpider;

import java.util.Calendar;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * 股票交易日志下载
 * @author wangxinning
 * 
 */
public class StockJiaoYiSpider extends BaseSpider {

	private static Logger logger = Logger.getLogger(StockJiaoYiSpider.class);

	private Map<String, Integer> timesMap = new HashMap<String, Integer>();
	private static final int TimesLimit = 3;//每天最大运行次数

	// 周末不下载, 每天下载二次，下午630点到730点间下载
	private boolean checkDate() throws ParseException {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());

		String dateHeader = DateFormatUtils.format(cal, "yyyyMMdd");
		if (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY
				&& cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
			// 上午
			long swStart = sdf.parse(dateHeader + "1830").getTime();
			long swEnd = sdf.parse(dateHeader + "2255").getTime();

			long current = cal.getTimeInMillis();
			if ((current >= swStart && current <= swEnd)) {
				return true;
			}
		}

		return false;
	}

	public List<ListPage> getSpiderHyperlinkList() {

//		try {
//			if (!checkDate()) {
//				return null;
//			}
//		} catch (Exception e) {
//			logger.error("股票行情下载列表生成出现异常", e);
//		}
//
//		String dateHeader = DateFormatUtils.format(new Date(), "yyyyMMdd");
//		if( timesMap.get(dateHeader) == null )//今天没运行过，清除以前的
//		{
//			timesMap.clear();
//		}
//		else if (timesMap.get(dateHeader) != null && timesMap.get(dateHeader) >= TimesLimit)//当天运行超过3次，退出
//		{
//			logger.info("今天行情下载超过" + TimesLimit + "次了，退出");
//			return null;
//		}
//
//		List<Hyperlink> retList = new ArrayList<Hyperlink>();
//
//		// 1.dbf文件目录
//		// 2.迭代路径
//		try {
//			List<Stock> stockList = getStockList();// 应该是解析文件得到
//			for (Stock stock : stockList) {
//				String sctypeStr = stock.getSctype() == 1 ? "sh" : "sz";
//				String url = StringUtils.replace(this.getConfigProject()
//						.getUrls(), "{sctype}", sctypeStr);
//				url = StringUtils.replace(url, "{code}", stock.getCode());
//				url = StringUtils.replace(url, "{yyyy}",
//						DateFormatUtils.format(new Date(), "yyyy"));
//				url = StringUtils.replace(url, "{MM}",
//						DateFormatUtils.format(new Date(), "MM"));
//				url = StringUtils.replace(url, "{dd}",
//						DateFormatUtils.format(new Date(), "dd"));
//
//				// http://market.finance.sina.com.cn/downxls.php?date=2013-07-09&symbol=sh600717
//				Hyperlink hyperlink = new Hyperlink();
//				hyperlink.setUrl(url);
//				hyperlink.setName(sctypeStr + stock.getCode());
//				retList.add(hyperlink);
//			}
//		} catch (Exception e) {
//			logger.error("解析股票DBF出现异常", e);
//			return null;
//		}
//
//		timesMap.put(dateHeader, timesMap.get(dateHeader) == null ? 1
//				: timesMap.get(dateHeader) + 1);
//		return retList;
		
		return null;
	}

	private List<Stock> getStockList() throws IOException, ParseException,
			xBaseJException {
		List<Stock> stockList = new ArrayList<Stock>();

		// 从内部寻找
		File shFile = DownloadAPI.searchFileByUrl("StockDBF", "show2003.dbf");
		File szFile = DownloadAPI.searchFileByUrl("StockDBF", "sjshq.dbf");

		if (shFile != null && shFile.exists()) {
			DBF shDBF = new DBF(shFile.toString());

			for (int i = 1; i < shDBF.getRecordCount(); i++) {//第一行无意义
				shDBF.read();

				String code = StringUtils.trimToEmpty(shDBF.getField("S1")
						.get());

				if (StringUtils.startsWith(code, "60")) {
					Stock stock = new Stock();
					stock.setCode(code);
					stock.setSctype(1);

					stockList.add(stock);
				}
			}
		}
		else
		{
			logger.error("上交所词典文件没有找到,show2003.dbf");
		}

		if (szFile != null && szFile.exists()) {
			DBF szDBF = new DBF(szFile.toString());

			for (int i = 1; i < szDBF.getRecordCount(); i++) {//第一行无意义
				szDBF.read();

				String code = StringUtils.trimToEmpty(szDBF.getField(1).get());

				if (StringUtils.startsWith(code, "00")
						|| StringUtils.startsWith(code, "30")) {
					Stock stock = new Stock();
					stock.setCode(code);
					stock.setSctype(2);

					stockList.add(stock);
				}
			}
		}
		else
		{
			logger.error("深交所词典文件没有找到,sjshq.dbf");
		}

		return stockList;
	}

	public String getCharset() {
		return "gbk";
	}

	class Stock {
		private int sctype;// 1上海2深圳

		public int getSctype() {
			return sctype;
		}

		public void setSctype(int sctype) {
			this.sctype = sctype;
		}

		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}

		private String code;// 股票代码
	}
}